from __future__ import annotations

import argparse
import os
from typing import Any, Dict
from dotenv import load_dotenv

from .config import load_smtp_config, RuntimeConfig
from .smtp_provider import SMTPEmailProvider
from .queue import MailQueue
from .dispatcher import MailDispatcher
from .logger import logger
from .redis_pool import RedisPool


def main() -> None:
    # Auto-load .env file at startup to ensure all local env vars take effect
    load_dotenv()
    
    parser = argparse.ArgumentParser(description="Report Mailer - Queue-driven mail sender")
    sub = parser.add_subparsers(dest="cmd")

    p_send = sub.add_parser("send", help="消费队列发送一次")
    p_send.add_argument("--dry-run", action="store_true", help="不实际发送，仅消费队列并标记成功")

    p_q = sub.add_parser("queue", help="队列管理与查询")
    p_q.add_argument("action", choices=["recent", "pending", "failed", "receipts", "search"], help="查询动作")
    p_q.add_argument("--limit", type=int, default=50)
    p_q.add_argument("--email", type=str, default=None, help="当 action=search 时指定email 片段")

    p_r = sub.add_parser("redis", help="Redis 连接测试与运维")
    p_r.add_argument("action", choices=["ping"], help="操作：ping")
    p_r.add_argument("--url", type=str, default=None, help="覆盖环境变量 REDIS_URL 的连接串")

    args = parser.parse_args()

    # 延迟加载 provider/dispatcher，以便查询命令不依赖SMTP配置
    rt_cfg = RuntimeConfig()
    queue = MailQueue(rt_cfg.db_path)

    if args.cmd == "queue":
        act = args.action
        if act == "recent":
            rows = queue.list_recent(args.limit)
        elif act == "pending":
            rows = queue.list_by_status("pending", args.limit)
        elif act == "failed":
            rows = queue.list_by_status("failed", args.limit)
        elif act == "receipts":
            rows = queue.list_receipts(args.limit)
        elif act == "search":
            if not args.email:
                print("--email 不能为空")
                return
            rows = queue.search_by_recipient(args.email, args.limit)
        else:
            print("未知动作")
            return
        for r in rows:
            print(r)
        return

    if args.cmd == "redis":
        act = args.action
        if act == "ping":
            try:
                pool = RedisPool(url=getattr(args, "url", None))
                client = pool.get_client()
                ok = client.ping()
                if ok:
                    print("PONG")
                else:
                    print("PING failed")
            except Exception as e:
                print(f"Redis ping error: {e}")
            return

    # 默认行为：send
    smtp_cfg = load_smtp_config()

    # Validate configurations
    try:
        smtp_cfg.validate()
        rt_cfg.validate()
        logger.info("Configuration validated successfully")
    except ValueError as e:
        logger.error(f"Configuration validation failed: {e}")
        print(f"Configuration error: {e}")
        return

    provider = SMTPEmailProvider(smtp_cfg)
    dispatcher = MailDispatcher(queue, provider, rt_cfg)

    dry_run_mode = getattr(args, "dry_run", False)
    if dry_run_mode:
        logger.info("Running in DRY-RUN mode")

    sent = dispatcher.run_once(dry_run=dry_run_mode)
    logger.info(f"Execution completed: sent={sent}")
    print(f"sent={sent}")


if __name__ == "__main__":
    main()


